package me.ianhe.wedding.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import me.ianhe.wedding.config.AppProperties;
import me.ianhe.wedding.entity.SystemUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author iHelin
 * @date 2019-08-08 18:57
 */
@Service
public class JwtTokenService {

    private static final String PREFIX = "Bearer ";

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AppProperties appConfig;

    public String generateToken(Authentication authentication) {
        SystemUser user = (SystemUser) authentication.getPrincipal();
        LocalDateTime currentTime = LocalDateTime.now();

        return Jwts.builder()
                .setSubject(user.getUsername())
                .setIssuer(appConfig.getJwtIssuer())
                .setIssuedAt((Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant())))
                .setExpiration(Date.from(currentTime.plusSeconds(appConfig.getJwtExpirationInSeconds())
                        .atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(SignatureAlgorithm.HS512, appConfig.getJwtSecret())
                .compact();
    }

    public String getUsernameFromToken(String token) {
        token = cutOutToken(token);
        Claims claims = Jwts.parser()
                .setSigningKey(appConfig.getJwtSecret())
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    public void validateToken(String authToken) {
//        try {
        authToken = cutOutToken(authToken);
        Jwts.parser().setSigningKey(appConfig.getJwtSecret()).parseClaimsJws(authToken);
//            return true;
//        } catch (SignatureException ex) {
//            logger.error("Invalid JWT signature");
//        } catch (MalformedJwtException ex) {
//            logger.error("Invalid JWT token");
//        } catch (ExpiredJwtException ex) {
//            logger.error("Expired JWT token");
//        } catch (UnsupportedJwtException ex) {
//            logger.error("Unsupported JWT token");
//        } catch (IllegalArgumentException ex) {
//            logger.error("JWT claims string is empty.");
//        }
//        return false;
    }

    private String cutOutToken(String bearerToken) {
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(PREFIX)) {
            return bearerToken.substring(PREFIX.length());
        }
        return null;
    }
}
